// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
import * as vscode from 'vscode';
import { GitExtension, RefType } from './typings/git';

// This method is called when your extension is activated
// Your extension is activated the very first time the command is executed
export function activate(context: vscode.ExtensionContext) {

	// Use the console to output diagnostic information (console.log) and errors (console.error)
	// This line of code will only be executed once when your extension is activated
	console.log('Congratulations, your extension "git-branches" is now active!');
	
	// The command has been defined in the package.json file
	// Now provide the implementation of the command with registerCommand
	// The commandId parameter must match the command field in package.json
	let removeDisposable = vscode.commands.registerCommand('git-branches.removeLocalBranch', async () => {
		// The code you place here will be executed every time your command is executed
		// Display a message box to the user
		const gitExtension = vscode.extensions.getExtension<GitExtension>('vscode.git')?.exports;
		const git = gitExtension?.getAPI(1);
		if (git?.state === 'initialized') {
			if (git.repositories.length === 0) { return; }

			const repo = git.repositories[0];
			const refs = await repo.getBranches({remote: false,sort: 'alphabetically'});
			const currentHead = repo.state.HEAD && repo.state.HEAD.name;

			const items = refs
			.filter(ref => ref.name !== currentHead)
			.map((ref) => {
				let description: string | undefined;
				if (ref.type === RefType.Head) {
					description = ref.commit;
				} else if (ref.type === RefType.Tag) {
					description = `Tag at ${ref.commit}`;
				}
				return {
					label: ref.name as string,
					description
				};
			});
			// 选择需要删除的分支
			const removes = await vscode.window.showQuickPick(items, {
				canPickMany: true,
				placeHolder: 'Which local branches do you want to delete?',
			});
			const success_removes = [];
			const failed_removes: string[] = [];
			if(removes && removes.length > 0) {
				for (let i = 0; i < removes.length; i++) {
					const remove = removes[i];
					try {
						// 非强制删除
						await repo.deleteBranch(remove.label);
						success_removes.push(remove);
					} catch (e: any) {
						console.log(`Error occurred while deleting : ${e}`);
						failed_removes.push(remove.label);
					}
				}
				// 成功删除记录数等于选择记录数
				if(success_removes.length > 0 && success_removes.length === removes.length) {
					vscode.window.showInformationMessage(`Delete ${success_removes.length} Branches Success!`);
				// 存在删除失败的分支
				} else {
					const yesButton = 'Yes';  
					const noButton = 'No';  
					vscode.window.showWarningMessage('Do you want to continue deleting all branches that are not fully merged?', yesButton, noButton).then( async (selection) => {  
						if (selection === yesButton) {  
							// 确认后强制删除
							try {
								failed_removes.forEach(async (failed_remove) => {
									await repo.deleteBranch(failed_remove, true);
								});
							} catch (error: any) {
								vscode.window.showErrorMessage(`Delete not fully merged branches failed: ${error.message}`);
								return;
							}
							vscode.window.showInformationMessage(`Delete ${removes.length} Branches Success!`);
						} else if (selection === noButton) {
							// 执行取消后的操作
							vscode.window.showWarningMessage(`Branch [${failed_removes.join(', ')}] Delete Failed!`);
						}  
					}); 
				}
			} else {
				vscode.window.showWarningMessage(`Please select the local branch you want to delete.`);
			}
		}
	});

	let createDisposable = vscode.commands.registerCommand('git-branches.createBranches', async () => {
		const gitExtension = vscode.extensions.getExtension<GitExtension>('vscode.git')?.exports;
		const git = gitExtension?.getAPI(1);
		if (git?.state === 'initialized') {
			if (git.repositories.length === 0) { return; }

			const repo = git.repositories[0];
			const refs = await repo.getRefs({sort: 'alphabetically'});

			const items = refs
			.filter((ref) => ref.type !== RefType.Tag)
			.map((ref) => {
				let description = ref.commit;
				return {
					label: ref.name as string,
					description
				};
			});
			// 选择需要创建的分支
			const base = await vscode.window.showQuickPick(items, {
				placeHolder: 'Which branch do you want to use for batch checkout?',
			});
			const copyName = await vscode.window.showInputBox({placeHolder: 'Please input the name of the branch, like feature/v6.1.0/feature1'});
			const count = Number(await vscode.window.showInputBox({
				placeHolder: 'Please enter the count of copy branches',
				validateInput: (val: string) => {
					const number = Number(val);
					return number > 0 ? undefined : 'Please enter a number.';
				}
			}));
			// 创建分支
			for (let index = 0; index < count; index++) {
				await repo.createBranch(`${copyName}_${index}`, true, base?.label);
			}
		}
	});

	context.subscriptions.push(removeDisposable);
	context.subscriptions.push(createDisposable);
}

// This method is called when your extension is deactivated
export function deactivate() {}
